<template>
  <view class="container">
    <!-- 顶部导航 -->
    <view class="navbar">
      <text class="navbar-title">我的</text>
      <view class="navbar-icon" @click="handleSettings">&#xe614;</view>
    </view>
    
    <!-- 登录状态显示 -->
    <view v-if="!isLoggedIn" class="login-prompt">
      <view class="login-avatar">
        <text class="login-icon">👤</text>
      </view>
      <text class="login-text">登录后享受更多功能</text>
      <button class="login-btn" @click="goToLogin">立即登录</button>
    </view>
    
    <!-- 个人信息区 -->
    <view v-else class="user-info">
      <image 
        class="user-avatar" 
        :src="userInfo.avatar || defaultAvatar" 
        @error="handleAvatarError"
      />
      <view class="user-meta">
        <text class="user-name">{{ userInfo.username || '未知用户' }}</text>
        <text class="user-level">{{ getUserStatusText(userInfo.status) }}</text>
        <text class="user-phone">{{ formatPhone(userInfo.phone) }}</text>
      </view>
      <button class="edit-btn" @click="editProfile">编辑资料</button>
    </view>
    
    <!-- 快捷功能区 -->
    <view class="quick-grid">
      <view 
        class="quick-item" 
        v-for="(item, idx) in quickList" 
        :key="idx"
        @click="handleQuickAction(item)"
      >
        <text :class="['iconfont', item.icon, 'quick-icon']"></text>
        <text class="quick-title">{{ item.title }}</text>
        <text class="quick-count">{{ item.count }}</text>
      </view>
    </view>
    
    <!-- 工具模块 -->
    <view class="tool-list">
      <view 
        class="tool-item" 
        v-for="(item, idx) in toolList" 
        :key="idx"
        @click="handleToolAction(item)"
      >
        <text :class="['iconfont', item.icon, 'tool-icon']"></text>
        <text class="tool-title">{{ item.title }}</text>
        <view v-if="item.badge" class="tool-badge">{{ item.badge }}</view>
        <text class="iconfont tool-arrow">&#xe65f;</text>
      </view>
    </view>
    
    <!-- 退出登录 -->
    <view v-if="isLoggedIn" class="logout-area">
      <button class="logout-btn" @click="handleLogout">退出登录</button>
    </view>
    
    <!-- 版本信息 -->
    <view class="version-info">
      <text class="app-version">闲置换钱 v1.0.0</text>
    </view>
  </view>
</template>

<script>
import { 
  getUserInfo, 
  isLoggedIn as checkLoginStatus, 
  logout, 
  fetchUserProfile, 
  USER_STATUS 
} from '@/utils/auth.js';
import { request } from '@/utils/request.js';

export default {
  data() {
    return {
      isLoggedIn: false,
      userInfo: {},
      defaultAvatar: 'https://picsum.photos/80/80?random=20',
      
      quickList: [
        { 
          id: 'publish', 
          icon: 'icon-apps', 
          title: '我的发布', 
          count: '0件',
          requireLogin: true 
        },
        { 
          id: 'favorite', 
          icon: 'icon-star', 
          title: '我的收藏', 
          count: '0件',
          requireLogin: true 
        },
        { 
          id: 'pending', 
          icon: 'icon-truck', 
          title: '待收货', 
          count: '0件',
          requireLogin: true 
        },
        { 
          id: 'payment', 
          icon: 'icon-card', 
          title: '待付款', 
          count: '0件',
          requireLogin: true 
        },
        { 
          id: 'review', 
          icon: 'icon-comment', 
          title: '待评价', 
          count: '0件',
          requireLogin: true 
        },
        { 
          id: 'service', 
          icon: 'icon-refresh', 
          title: '售后服务', 
          count: '0件',
          requireLogin: true 
        }
      ],
      
      toolList: [
        { 
          id: 'orders', 
          icon: 'icon-order', 
          title: '我的订单',
          requireLogin: true 
        },
        { 
          id: 'address', 
          icon: 'icon-location', 
          title: '地址管理',
          requireLogin: true 
        },
        { 
          id: 'coupon', 
          icon: 'icon-ticket', 
          title: '优惠券', 
          badge: '0张',
          requireLogin: true 
        },
        { 
          id: 'customer', 
          icon: 'icon-question', 
          title: '客服中心' 
        },
        { 
          id: 'security', 
          icon: 'icon-shield', 
          title: '安全中心',
          requireLogin: true 
        },
        { 
          id: 'settings', 
          icon: 'icon-setting', 
          title: '设置' 
        }
      ]
    }
  },
  
  onShow() {
    // 每次显示页面时检查登录状态
    this.checkLoginStatus();
  },
  
  onLoad() {
    this.checkLoginStatus();
    this.loadUserData();
  },
  
  methods: {
    // 检查登录状态
    checkLoginStatus() {
      this.isLoggedIn = checkLoginStatus();
      if (this.isLoggedIn) {
        this.userInfo = getUserInfo() || {};
      } else {
        this.userInfo = {};
      }
    },
    
    // 加载用户数据
    async loadUserData() {
      if (!this.isLoggedIn) return;
      
      try {
        // 获取最新用户信息
        const userProfile = await fetchUserProfile();
        this.userInfo = userProfile;
        
        // 加载用户统计数据
        await this.loadUserStats();
        
      } catch (error) {
        console.error('加载用户数据失败:', error);
      }
    },
    
    // 加载用户统计数据
    async loadUserStats() {
      try {
        // 这里可以调用相应的API获取用户的各种统计数据
        // 暂时使用模拟数据
        this.quickList = this.quickList.map(item => ({
          ...item,
          count: this.getRandomCount() + '件'
        }));
        
        this.toolList = this.toolList.map(item => {
          if (item.id === 'coupon') {
            return { ...item, badge: this.getRandomCount() + '张' };
          }
          return item;
        });
        
      } catch (error) {
        console.error('加载用户统计数据失败:', error);
      }
    },
    
    // 生成随机数量（用于演示）
    getRandomCount() {
      return Math.floor(Math.random() * 10);
    },
    
    // 跳转到登录页
    goToLogin() {
      uni.navigateTo({
        url: '/pages/login/index'
      });
    },
    
    // 处理快捷功能点击
    handleQuickAction(item) {
      if (item.requireLogin && !this.isLoggedIn) {
        this.showLoginPrompt();
        return;
      }
      
      switch (item.id) {
        case 'publish':
          this.goToMyPublish();
          break;
        case 'favorite':
          this.goToMyFavorite();
          break;
        case 'pending':
        case 'payment':
        case 'review':
          this.goToOrderList(item.id);
          break;
        case 'service':
          this.goToAfterService();
          break;
        default:
          uni.showToast({
            title: '功能开发中',
            icon: 'none'
          });
      }
    },
    
    // 处理工具功能点击
    handleToolAction(item) {
      if (item.requireLogin && !this.isLoggedIn) {
        this.showLoginPrompt();
        return;
      }
      
      switch (item.id) {
        case 'orders':
          this.goToMyOrders();
          break;
        case 'address':
          this.goToAddressManage();
          break;
        case 'coupon':
          this.goToCouponList();
          break;
        case 'customer':
          this.contactCustomerService();
          break;
        case 'security':
          this.goToSecurityCenter();
          break;
        case 'settings':
          this.goToSettings();
          break;
        default:
          uni.showToast({
            title: '功能开发中',
            icon: 'none'
          });
      }
    },
    
    // 显示登录提示
    showLoginPrompt() {
      uni.showModal({
        title: '提示',
        content: '此功能需要登录后使用',
        confirmText: '去登录',
        success: (res) => {
          if (res.confirm) {
            this.goToLogin();
          }
        }
      });
    },
    
    // 编辑个人资料
    editProfile() {
      uni.navigateTo({
        url: '/pages/profile/edit'
      });
    },
    
    // 处理设置点击
    handleSettings() {
      this.goToSettings();
    },
    
    // 退出登录
    handleLogout() {
      uni.showModal({
        title: '确认退出',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            logout();
          }
        }
      });
    },
    
    // 头像加载失败处理
    handleAvatarError() {
      console.log('头像加载失败，使用默认头像');
    },
    
    // 格式化手机号
    formatPhone(phone) {
      if (!phone) return '';
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    },
    
    // 获取用户状态文本
    getUserStatusText(status) {
      switch (status) {
        case USER_STATUS.NORMAL:
          return 'V1 普通用户';
        case USER_STATUS.DISABLED:
          return '账号已禁用';
        case USER_STATUS.LOCKED:
          return '账号已锁定';
        default:
          return '未知状态';
      }
    },
    
    // 跳转方法
    goToMyPublish() {
      uni.navigateTo({
        url: '/pages/user/publish'
      });
    },
    
    goToMyFavorite() {
      uni.navigateTo({
        url: '/pages/user/favorite'
      });
    },
    
    goToOrderList(type) {
      uni.navigateTo({
        url: `/pages/order/list?type=${type}`
      });
    },
    
    goToMyOrders() {
      uni.navigateTo({
        url: '/pages/order/list?type=buyer'
      });
    },
    
    goToAfterService() {
      uni.navigateTo({
        url: '/pages/service/index'
      });
    },
    
    goToAddressManage() {
      uni.navigateTo({
        url: '/pages/address/list'
      });
    },
    
    goToCouponList() {
      uni.navigateTo({
        url: '/pages/coupon/list'
      });
    },
    
    goToAddressManage() {
      uni.navigateTo({
        url: '/pages/address/index'
      });
    },
    
    goToSecurityCenter() {
      uni.navigateTo({
        url: '/pages/security/index'
      });
    },
    
    goToSettings() {
      uni.navigateTo({
        url: '/pages/settings/index'
      });
    },
    
    contactCustomerService() {
      uni.showActionSheet({
        itemList: ['在线客服', '客服电话', '意见反馈'],
        success: (res) => {
          switch (res.tapIndex) {
            case 0:
              uni.showToast({
                title: '在线客服功能开发中',
                icon: 'none'
              });
              break;
            case 1:
              uni.makePhoneCall({
                phoneNumber: '400-123-4567'
              });
              break;
            case 2:
              uni.navigateTo({
                url: '/pages/feedback/index'
              });
              break;
          }
        }
      });
    }
  }
}
</script>

<style scoped>
/* 基本样式 */
.container { 
  background: #f5f5f5; 
  min-height: 100vh; 
}

/* 导航栏 */
.navbar { 
  display: flex; 
  align-items: center; 
  justify-content: space-between; 
  padding: 12px 16px; 
  background: #fff; 
  border-bottom: 1px solid #eee; 
}

.navbar-title { 
  font-size: 20px; 
  font-weight: bold; 
}

.navbar-icon { 
  font-family: "iconfont"; 
  font-size: 22px; 
  color: #888; 
  cursor: pointer;
}

/* 登录提示 */
.login-prompt {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40px 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #fff;
}

.login-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
}

.login-icon {
  font-size: 36px;
}

.login-text {
  font-size: 16px;
  margin-bottom: 20px;
  opacity: 0.9;
}

.login-btn {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 20px;
  padding: 8px 24px;
  font-size: 14px;
}

/* 用户信息区 */
.user-info { 
  background: linear-gradient(90deg, #FF5E5E 60%, #FFB800 100%); 
  padding: 24px 16px; 
  display: flex; 
  align-items: center; 
  color: #fff; 
}

.user-avatar { 
  width: 64px; 
  height: 64px; 
  border-radius: 50%; 
  border: 2px solid #fff; 
}

.user-meta { 
  margin-left: 12px; 
  flex: 1; 
}

.user-name { 
  font-size: 18px; 
  font-weight: bold; 
}

.user-level { 
  font-size: 13px; 
  opacity: 0.9; 
  margin-top: 4px; 
  display: block; 
}

.user-phone {
  font-size: 12px; 
  opacity: 0.8; 
  margin-top: 2px; 
  display: block;
}

.edit-btn { 
  background: transparent; 
  border: 1px solid #fff; 
  color: #fff; 
  border-radius: 16px; 
  padding: 4px 16px; 
  font-size: 13px; 
  margin-left: auto; 
}

/* 快捷功能网格 */
.quick-grid { 
  display: grid; 
  grid-template-columns: repeat(3, 1fr); 
  gap: 12px; 
  padding: 16px; 
}

.quick-item { 
  background: #fff; 
  border-radius: 8px; 
  display: flex; 
  flex-direction: column; 
  align-items: center; 
  padding: 12px 0;
  cursor: pointer;
  transition: all 0.3s;
}

.quick-item:active {
  transform: scale(0.95);
  background: #f8f8f8;
}

.quick-icon { 
  font-size: 22px; 
  color: #FF5E5E; 
}

.quick-title { 
  font-size: 13px; 
  margin-top: 6px; 
  color: #333; 
}

.quick-count { 
  font-size: 12px; 
  color: #888; 
  margin-top: 2px; 
}

/* 工具列表 */
.tool-list { 
  margin: 16px; 
  background: #fff; 
  border-radius: 8px; 
  overflow: hidden; 
}

.tool-item { 
  display: flex; 
  align-items: center; 
  padding: 14px 16px; 
  border-bottom: 1px solid #f0f0f0; 
  position: relative;
  cursor: pointer;
  transition: background 0.3s;
}

.tool-item:last-child { 
  border-bottom: none; 
}

.tool-item:active {
  background: #f8f8f8;
}

.tool-icon { 
  font-size: 20px; 
  color: #888; 
  width: 28px; 
}

.tool-title { 
  flex: 1; 
  font-size: 15px; 
  color: #333; 
}

.tool-badge { 
  background: #FF5E5E22; 
  color: #FF5E5E; 
  font-size: 12px; 
  border-radius: 10px; 
  padding: 2px 8px; 
  margin-left: 8px; 
}

.tool-arrow { 
  font-size: 16px; 
  color: #bbb; 
}

/* 退出登录区域 */
.logout-area { 
  text-align: center; 
  margin: 32px 16px 16px; 
}

.logout-btn { 
  color: #FF5E5E; 
  background: #fff; 
  border: 1px solid #FF5E5E; 
  border-radius: 8px;
  font-size: 15px;
  padding: 12px 0;
  width: 100%;
}

/* 版本信息 */
.version-info {
  text-align: center;
  margin: 16px 0 32px;
}

.app-version { 
  color: #bbb; 
  font-size: 12px; 
}
</style>
